package com.app.shop.util.weixin;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.app.shop.constants.WeixinConstants.WEIXINPARAMS;
import com.app.shop.entity.weixin.WxPayDto;
import com.app.shop.util.PropertyAccessor;
import com.app.shop.util.SysModel;
import net.sf.json.JSONObject;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.apache.log4j.Logger;


/**
 * 
 * @ClassName: GetWxOpenId 
 * @Description: TODO(获取微信OpenId) 
 * @author Garfield Miao
 * @date 2016年5月23日
 */
public class GetWxOpenId {

	private static final Logger LOG = Logger.getLogger(GetWxOpenId.class);

	public String getOpenId(String code) throws Exception
			 {
			 	SysModel sysModel = new SysModel();
			 	HttpClient client = new HttpClient();
		String openid = null;
		try {
			HttpMethod method = getGetMethod(code);
			method.getParams().setParameter(
					HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
			client.executeMethod(method);
			String jsonArray = null;
			JSONObject data = null;
			try {
				LOG.info("获取openId请求的code为：" + code);
				// 设置编码
				@SuppressWarnings({ "resource" })
				InputStream inps = method.getResponseBodyAsStream();
				InputStreamReader isr = new InputStreamReader(inps, "UTF-8");// 读取
				BufferedReader br = new BufferedReader(isr);
				jsonArray = br.readLine();
				JSONObject jsonData = new JSONObject();
				jsonData.put("jsonData", jsonArray);
				data = jsonData.getJSONObject("jsonData");
				String jsonString = data.toString();
				LOG.info("获取openId：" + data.toString());
				if (jsonString.indexOf("errcode") != -1) {
					// 错误报错{"errcode":-1,"errmsg":"system error, hints: [ req_id: beK7lA0521ns72 ]"}
					LOG.error("微信支付异常FAIL：" + data.toString());
					return openid;
				}
				if (jsonString.indexOf("openid") != -1) {
					// 获取到的openId
					openid = data.getString("openid");
				}
				if (StringUtils.isBlank(openid)) {
					LOG.error("微信支付异常openId为空" + data.toString());
					return openid;
				}
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
			} finally {
				// Release the connection.
				method.releaseConnection();
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			LOG.error("微信支付异常",e);
		}
		return openid;
	}

	/**
	 * 
	 * 使用 GET 方式提交数据
	 * 
	 * @return
	 * @throws
	 */
	private static HttpMethod getGetMethod(String code)
			throws Exception {
		return new GetMethod(PropertyAccessor.getProperty(WEIXINPARAMS.GETOPENBYTYPE
				.getCode()) + code);
	}

	//小程序专用
	public WxPayDto getOpenIdByType(String code) throws Exception {

		HttpClient client = new HttpClient();
		String openid = null;
		String session_key=null;
		String unionId=null;
		WxPayDto dto=new WxPayDto();
		try {
			HttpMethod method = getGetMethodByType(code);
			method.getParams().setParameter(
					HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
			client.executeMethod(method);
			String jsonArray = null;
			JSONObject data = null;
			try {
				LOG.info("微信小程序获取openId请求的code为：" + code);
				// 设置编码
				@SuppressWarnings({ "resource" })
				InputStream inps = method.getResponseBodyAsStream();
				InputStreamReader isr = new InputStreamReader(inps, "UTF-8");// 读取
				BufferedReader br = new BufferedReader(isr);
				jsonArray = br.readLine();
				JSONObject jsonData = new JSONObject();
				jsonData.put("jsonData", jsonArray);
				data = jsonData.getJSONObject("jsonData");
				String jsonString = data.toString();
				LOG.info("获取openId：" + data.toString());
				if (jsonString.indexOf("errcode") != -1) {
					// 错误报错{"errcode":-1,"errmsg":"system error, hints: [ req_id: beK7lA0521ns72 ]"}
					LOG.error("微信支付异常FAIL：" + data.toString());
					return dto;
				}
				if (jsonString.indexOf("openid") != -1) {
					// 获取到的openId
					openid = data.getString("openid");
					dto.setOpenId(openid);
				}
				if (jsonString.indexOf("session_key") != -1) {
					// 获取到的session_key
					session_key = data.getString("session_key");
					dto.setSessionKey(session_key);
				}
				if (jsonString.indexOf("unionid") != -1) {
					// 获取到的session_key
					unionId = data.getString("unionid");
					dto.setUnionId(unionId);
				}
				String webankAppId = PropertyAccessor.getProperty("wxxcx_wzyh_webankAppId");
				dto.setWebankAppId(webankAppId);
				if (StringUtils.isBlank(openid)) {
					LOG.error("微信支付异常openId为空" + data.toString());
					return dto;
				}
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
			} finally {
				// Release the connection.
				method.releaseConnection();
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			LOG.error("微信支付异常",e);
		}
		return dto;
	}

	/**
	 * 
	 * 使用 GET 方式提交数据
	 * 
	 * @return
	 */
	private static HttpMethod getGetMethodByType(String code)
			throws Exception {
		StringBuffer s=new StringBuffer();
				String url = PropertyAccessor.getProperty(WEIXINPARAMS.GETOPENBYTYPE.getCode());
				
				if(StringUtils.isNotBlank(url)){
					s.append(url);
					s.append("&");
					s.append("appid");
					s.append("=");
					s.append(PropertyAccessor.getProperty(WEIXINPARAMS.SELFAPPID.getCode()));
					s.append("&");
					s.append("secret");
					s.append("=");
					s.append(PropertyAccessor.getProperty(WEIXINPARAMS.SELFAPPSECRET.getCode()));
					s.append("&");
					s.append("js_code");
					s.append("=");
				}
			return new GetMethod(s.toString() + code);
	}
	
	
	
	
	
	
	
	
	

}
